package com.example.Android_test.util;

import android.os.Handler;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: anpi0413
 * Date: 23.05.13
 * Time: 11:25
 * To change this template use File | Settings | File Templates.
 */
public class DownStepSecondTimer implements Runnable {
    public static final int DEFAULT_TIME = 10;

    Integer startFromSecond;
    private List<ActionListener> stepListeners = new ArrayList<ActionListener>();
    private List<ActionListener> finishListeners = new ArrayList<ActionListener>();
    private Handler myHandler = new Handler();


    public DownStepSecondTimer() {
        this.startFromSecond = DEFAULT_TIME; // default value
    }

    public DownStepSecondTimer(int startSecond) {
        this.startFromSecond = startSecond;
    }

    public void start() {
        DownStepSecondTimer customTimer = new DownStepSecondTimer(startFromSecond);
        for (ActionListener listener : finishListeners) {
            customTimer.addFinishListener(listener);
        }
        for (ActionListener listener : stepListeners) {
            customTimer.addStepListener(listener);
        }

        myHandler.post(customTimer);
    }

    public void startWithInitialSeconds(int sec) {
        setStartFromSecond(sec);
        start();
    }

    @Override
    public void run() {
        stepFireEvent(startFromSecond);

        if (startFromSecond <= 0) {
            finishFireEvent(null);
            return;
        }

        startFromSecond--;

        DownStepSecondTimer customTimer = new DownStepSecondTimer(startFromSecond);
        for (ActionListener listener : finishListeners) {
            customTimer.addFinishListener(listener);
        }
        for (ActionListener listener : stepListeners) {
            customTimer.addStepListener(listener);
        }

        myHandler.postDelayed(customTimer, 1000);
    }

    public void setStartFromSecond(int startFromSecond) {
        this.startFromSecond = startFromSecond;
    }

    public void addStepListener(ActionListener listener) {
        stepListeners.add(listener);
    }

    public void removeStepListener(ActionListener listener) {
        stepListeners.remove(listener);
    }

    private void stepFireEvent(Object event) {
        for (ActionListener listener : stepListeners) {
            listener.actionPerformed(event);
        }
    }

    public void addFinishListener(ActionListener listener) {
        finishListeners.add(listener);
    }

    public void removeFinishListener(ActionListener listener) {
        finishListeners.remove(listener);
    }

    private void finishFireEvent(Object event) {
        for (ActionListener listener : finishListeners) {
            listener.actionPerformed(event);
        }
    }

    public interface ActionListener {
        public void actionPerformed(Object o);
    }
}
